<template lang="html">
  <div class="editor" v-loading="imgLoading">
    <div ref="toolbar" class="toolbar"></div>
    <div
      ref="editor"
      class="text"
      :style="{ height: height ? height + 'px' : '' }"
    ></div>
  </div>
</template>

<script>
  import E from 'wangeditor'
  export default {
    data() {
      return {
        editor: null,
        info_: null,
        imgLoading: false
      }
    },
    model: {
      prop: 'value',
      event: 'change'
    },
    props: {
      value: {
        type: String,
        default: ''
      },
      height: {
        type: Number,
        default: 0
      },
      isClear: {
        type: Boolean,
        default: false
      }
    },
    watch: {
      isClear(val) {
        // 触发清除文本域内容
        if (val) {
          this.editor.txt.clear()
          this.info_ = null
        }
      },
      value(val) {
        // 保证光标不会重新回到最后
        if (val != this.info_) {
          // 使用 v-model 时，设置初始值
          this.editor.txt.html(val)
        }
      }
    },
    mounted() {
      this.seteditor()
      this.$EventBus.$on('insert_content', (value) => {
        this.editor.cmd.do('insertHTML', value)
      })
    },
    methods: {
      seteditor() {
        const _this = this
        this.editor = new E(this.$refs.toolbar, this.$refs.editor)

        this.editor.config.zIndex = 0

        // this.editor.config.menus = [
        //   'bold',
        //   'head',
        //   'link',
        //   'italic',
        //   'underline'
        // ]

        this.editor.config.customAlert = function (s) {
          _this.$message.error(s)
        }
        this.editor.config.onchange = (html) => {
          _this.info_ = html // 绑定当前逐渐地值
          _this.$emit('change', _this.info_) // 将内容同步到父组件中
        }

        // 创建富文本编辑器
        this.editor.create()
        if (this.value) {
          this.editor.txt.html(this.value)
        }
      }
    },
    beforeDestroy() {
      this.editor.destroy()
      this.editor = null
    }
  }
</script>

<style lang="css">
  .editor {
    width: 100%;
    margin: 0 auto;
  }
  .toolbar {
    border: 1px solid #ccc;
  }
  .text {
    border: 1px solid #ccc;
    height: 100%;
  }
  .w-e-text-container {
    height: 100% !important;
  }
</style>
